package com.ruoyi.system.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.OaProjectInitiation;
import com.ruoyi.system.domain.OaSuppliers;
import com.ruoyi.system.service.IOaProjectInitiationService;
import com.ruoyi.system.service.IOaSuppliersService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.OaOther;
import com.ruoyi.system.service.IOaOtherService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 采购Controller
 *
 * @author ruoyi
 * @date 2025-03-11
 */
@RestController
@RequestMapping("/system/other")
@Transactional
public class OaOtherController extends BaseController {
    @Autowired
    private IOaOtherService oaOtherService;
    @Autowired
    private IOaSuppliersService iOaSuppliersService;
    @Autowired
    private IOaProjectInitiationService oaProjectInitiationService;

    /**
     * 查询采购列表
     */
    @PreAuthorize("@ss.hasPermi('system:other:list')")
    @GetMapping("/list")
    public TableDataInfo list(OaOther oaOther) {
        startPage();
        List<OaOther> list = oaOtherService.selectOaOtherList(oaOther);
        return getDataTable(list);
    }

    /**
     * 导出采购列表
     */
    @PreAuthorize("@ss.hasPermi('system:other:export')")
    @Log(title = "采购", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, OaOther oaOther) {
        List<OaOther> list = oaOtherService.selectOaOtherList(oaOther);
        ExcelUtil<OaOther> util = new ExcelUtil<OaOther>(OaOther.class);
        util.exportExcel(response, list, "采购数据");
    }

    /**
     * 获取采购详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:other:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(oaOtherService.selectOaOtherById(id));
    }

    /**
     * 新增采购
     */
    @PreAuthorize("@ss.hasPermi('system:other:add')")
    @Log(title = "采购", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody OaOther oaOther) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 获取供应商名称
        String supplier = oaOther.getSupplier();
        // 创建OaSuppliers对象
        OaSuppliers oaSuppliers = new OaSuppliers();
        // 设置供应商名称
        oaSuppliers.setSupplierName(supplier);
        // 查询供应商列表
        List<OaSuppliers> oaSuppliers1 = iOaSuppliersService.selectOaSuppliersList(oaSuppliers);
        if (oaSuppliers1.isEmpty()) {
            //创建供应商
            oaSuppliers.setCreateTime(new Date());
            iOaSuppliersService.insertOaSuppliers(oaSuppliers);
        }
        //生成成本率
        String initiationId = oaOther.getInitiationId();
        OaProjectInitiation oaProjectInitiation = oaProjectInitiationService.selectOaProjectInitiationById(Integer.valueOf(initiationId));
        if (!loginUser.getUsername().equals(oaProjectInitiation.getInitiationPersonInCharge())) {
            throw new RuntimeException("当前用户不是项目负责人，无法填写");
        }
        OaOther oaOther1 = new OaOther();
        oaOther1.setInitiationId(initiationId);
        List<OaOther> oaOthers = oaOtherService.selectOaOtherList(oaOther1);
        BigDecimal costRate = BigDecimal.ZERO;

        // 累加所有 OaOther 对象的总预算
        for (OaOther other : oaOthers) {
            if (other.getTotalBudget() != null) {
                costRate = costRate.add(other.getTotalBudget());
            }
        }
        // 获取报价
        BigDecimal quotedPrice = oaProjectInitiation.getQuotedPrice();

        if (quotedPrice != null && quotedPrice.compareTo(BigDecimal.ZERO) != 0) {
            // 计算成本率，乘以 100 并保留两位小数
            BigDecimal costRatePercentage = costRate.divide(quotedPrice, 4, BigDecimal.ROUND_HALF_UP)
                    .multiply(BigDecimal.valueOf(100))
                    .setScale(2, BigDecimal.ROUND_HALF_UP);
            // 设置成本率到预留字段 1
            oaProjectInitiation.setReservedField1(costRatePercentage.toPlainString() + "%");
            oaProjectInitiation.setBudgetCost(costRate);
        } else {
            // 报价为 null 或为 0 的情况
            oaProjectInitiation.setReservedField1("报价为 null 或为 0 的情况 无法计算");
        }
        oaProjectInitiation.setManagementApproval("待审批");
        oaProjectInitiation.setManagementApprovala("待审批");
        oaProjectInitiationService.updateOaProjectInitiation(oaProjectInitiation);
        return toAjax(oaOtherService.insertOaOther(oaOther));
    }

    /**
     * 修改采购
     */
    @PreAuthorize("@ss.hasPermi('system:other:edit')")
    @Log(title = "采购", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody OaOther oaOther) {
        OaProjectInitiation oaProjectInitiation = oaProjectInitiationService.selectOaProjectInitiationById(Integer.valueOf(oaOther.getInitiationId()));
            oaProjectInitiation.setManagementApprovala("待审批");
            oaProjectInitiation.setManagementApproval("待审批");
        oaProjectInitiationService.updateOaProjectInitiation(oaProjectInitiation);
        return toAjax(oaOtherService.updateOaOther(oaOther));
    }

    /**
     * 删除采购
     */
    @PreAuthorize("@ss.hasPermi('system:other:remove')")
    @Log(title = "采购", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(oaOtherService.deleteOaOtherByIds(ids));
    }


    @PostMapping("/adds")
    public AjaxResult adds(@RequestBody List<OaOther> oaOthers) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 初始化立项id
        String initiationId = null;
        // 遍历oaOthers列表
        for (OaOther other : oaOthers) {
            initiationId = other.getInitiationId();
            // 获取供应商名称
            String supplier = other.getSupplier();
            // 创建OaSuppliers对象
            OaSuppliers oaSuppliers = new OaSuppliers();
            // 设置供应商名称
            oaSuppliers.setSupplierName(supplier);
            // 查询供应商列表
            List<OaSuppliers> oaSuppliers1 = iOaSuppliersService.selectOaSuppliersList(oaSuppliers);
            if (oaSuppliers1.isEmpty()) {
                //创建供应商
                oaSuppliers.setCreateTime(new Date());
                iOaSuppliersService.insertOaSuppliers(oaSuppliers);
            }
            // 插入其他信息
            oaOtherService.insertOaOther(other);
        }
        //生成成本率
        OaProjectInitiation oaProjectInitiation = oaProjectInitiationService.selectOaProjectInitiationById(Integer.valueOf(initiationId));
        if (!loginUser.getUsername().equals(oaProjectInitiation.getInitiationPersonInCharge())) {
            throw new RuntimeException("当前用户不是项目负责人，无法填写");
        }
        OaOther oaOther1 = new OaOther();
        oaOther1.setInitiationId(initiationId);
        List<OaOther> oaOthers1 = oaOtherService.selectOaOtherList(oaOther1);
        BigDecimal costRate = BigDecimal.ZERO;

        // 累加所有 OaOther 对象的总预算
        for (OaOther other : oaOthers1) {
            if (other.getTotalBudget() != null) {
                costRate = costRate.add(other.getTotalBudget());
            }
        }
        // 获取报价
        BigDecimal quotedPrice = oaProjectInitiation.getQuotedPrice();

        if (quotedPrice != null && quotedPrice.compareTo(BigDecimal.ZERO) != 0) {
            // 计算成本率，乘以 100 并保留两位小数
            BigDecimal costRatePercentage = costRate.divide(quotedPrice, 4, BigDecimal.ROUND_HALF_UP)
                    .multiply(BigDecimal.valueOf(100))
                    .setScale(2, BigDecimal.ROUND_HALF_UP);
            // 设置成本率到预留字段 1
            oaProjectInitiation.setReservedField1(costRatePercentage.toPlainString() + "%");
            oaProjectInitiation.setBudgetCost(costRate);
        } else {
            // 报价为 null 或为 0 的情况
            oaProjectInitiation.setReservedField1("报价为 null 或为 0 的情况 无法计算");
        }
        oaProjectInitiation.setManagementApproval("未审批");
        oaProjectInitiation.setManagementApprovala("未审批");
        oaProjectInitiationService.updateOaProjectInitiation(oaProjectInitiation);
        // 返回批量添加成功
        return AjaxResult.success("批量添加成功");
    }

    @PutMapping("/edits")
    public AjaxResult edits(@RequestBody List<OaOther> oaOthers) {
        for (OaOther other : oaOthers) {
            oaOtherService.updateOaOther(other);
        }
        return AjaxResult.success("批量修改成功");
    }

    //根据供应商获取之前填写的数据（粉表）
    @GetMapping("/getDataBySupplierId")
    public AjaxResult getDataBySupplierId(String supplier) {
        OaOther oaOther = new OaOther();
        oaOther.setSupplier(supplier);
        List<OaOther> oaOthers = oaOtherService.selectOaOtherList(oaOther);
        return AjaxResult.success(oaOthers);
    }

}
